package com.larry.set;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ProjectName JUC
 * @Author larry
 * @Date 14:06 2021/7/12
 * @Description list线程不安全--并发修改异常
 **/
public class ThreadDemo4 {
    public static void main(String[] args) {

//        List<String> list = new ArrayList<>();


        /**
         * 源码
         * public synchronized void addElement(E var1) {
         *         ++this.modCount;
         *         this.ensureCapacityHelper(this.elementCount + 1);
         *         this.elementData[this.elementCount++] = var1;
         *     }
         */
//        List<String> list = new Vector<>();


        /**
         * Collections
         */
//        List<String> list = Collections.synchronizedList(new ArrayList<>());


        /**
         *  写时复制
         *  public boolean add(E var1) {
         *         ReentrantLock var2 = this.lock;
         *         var2.lock();
         *
         *         boolean var6;
         *         try {
         *             Object[] var3 = this.getArray();
         *             int var4 = var3.length;
         *             Object[] var5 = Arrays.copyOf(var3, var4 + 1);
         *             var5[var4] = var1;
         *             this.setArray(var5);
         *             var6 = true;
         *         } finally {
         *             var2.unlock();
         *         }
         *
         *         return var6;
         *     }
         */
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}
